
set seed 12345

use "${source_data}\Data_Estimation_Elasticities.dta", clear
keep s_id
duplicates drop
sort s_id
save "${replicated_data}\s_id_b.dta", replace 


local endloop = 500
qui forval iter=1(1)`endloop' {
	global dirnum = `iter'
	set seed ${dirnum}
	noi dis "> ${dirnum}"
	global bootlocal = "${boot}\${dirnum}"
	!rm -rf "${bootlocal}/"
	cap mkdir "${bootlocal}"
	*cd ${directoryfile}
		!cp -r * "${bootlocal}"
	cd "${bootlocal}"

	clear
	use "${replicated_data}\s_id_b.dta",clear
	* Draw bootstrap sample for the entire seller
	bsample
	keep s_id
	
	sort s_id
	gen s_id_b = 10000+_n
	sort s_id
	
	saveold tmp_bsample${dirnum}, replace

		* merge in bootstrap ID's (note duplicates)
		use "${source_data}\Data_Estimation_Elasticities.dta",clear
		sort s_id *
		joinby s_id using tmp_bsample${dirnum}
			rename s_id s_id_original
			rename s_id_b s_id
			drop if s_id==.
		
	if $dirnum!=0 {
		local iteratemax = ",iterate(2000)"
		}
	if $dirnum==0 {
		local iteratemax = ""
		}

		save tmp_bsample${dirnum}, replace
	    do "${code}\Estimation_Elasticities.do"


		capture erase "${boot}\${dirnum}"
		!rm -rf "${boot}\${dirnum}"
}


* Bootstrap SEs
global I = 500
use "${boot}\elasticities_1.dta", clear
forval i = 2/$I {
	append using "${boot}\elasticities_`i'.dta"
	}
	drop if dirnum==.


	foreach v of varlist theta* beta*  {
		egen `v'_mean = mean(`v')
		gen dev = (`v'-`v'_mean)^2
		egen sumdev = sum(dev)
		replace sumdev = (sumdev/${I})^.5
		gen `v'_se = sumdev
		drop dev sumdev
		_pctile `v', percentiles(2.5 97.5)
		gen `v'_lb=r(r1)
		gen `v'_ub=r(r2)

		}
	keep *_mean *_se *_lb *_ub
	duplicates drop
	rename *_mean *_1
	rename *_se *_2
	rename *_lb *_3
    rename *_ub *_4
    xpose, varname clear
    
    capture drop i
	gen i=substr(_varname,1,(strlen(_varname)-2))
	capture drop j	
    gen j=substr(_varname,-2,2)
    drop _varname
	reshape wide v1, i(i) j(j) string
	rename v1_1 coeff
	rename v1_2 se
	gen tstat = coeff/se
	rename v1_3 ci_lb
	rename v1_4 ci_ub
    rename i estimation

	save "${replicated_data}\Bootstrapped_Elasticities.dta", replace
	use "${replicated_data}\Bootstrapped_Elasticities.dta", clear
	
* ------------------------------------------------------------------------------ *
* TABLE E4. Elasticites and Return to Scale
* ------------------------------------------------------------------------------ *

	do "${floats}\TableE4.do"
	
